<?php

namespace App\Livewire;

use App\Events\MessageSent;
use App\Models\ChatMessage;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
use Livewire\Component;

class ChatComponent extends Component
{
    public $user;
    public $new_message = '';
    public $sender_id;
    public $receiver_id;
    public $messages;
    public function render()
    {
        return view('livewire.chat-component');
    }
    public function sendMessage()
    {
        $message = ChatMessage::create([
            'sender_id' => $this->sender_id,
            'receiver_id' => $this->receiver_id,
            'message' => $this->new_message,
        ]);
        $this->appendMessage($message);
        broadcast(new MessageSent($message))->toOthers();
        $this->new_message = '';
    }
    public function mount($user_id)
    {
        $this->sender_id = Auth::id();
        $this->receiver_id = $user_id;
        $this->user = User::find($user_id);
        $messages = ChatMessage::where(function ($query) {
            $query->where('sender_id', $this->sender_id)
                ->where('receiver_id', $this->receiver_id);
            $query->orWhere('sender_id', $this->receiver_id)
                ->where('receiver_id', $this->sender_id);
        })
            ->with('sender:id,name')
            ->with('receiver:id,name')

            ->get();
        $messages->each(function ($message) {
            $this->appendMessage($message);
        });
        // dd($this->messages);
    }
    #[On('echo-private:chat-channel.{sender_id},MessageSent')]
    public function listenMessage($event)
    {
        $chatMessage = ChatMessage::with('sender:id,name')
            ->with('receiver:id,name')->find($event['chatMessage']['id']);
        $this->appendMessage($chatMessage);
    }
    public function appendMessage($message)
    {
        $this->messages[] = [
            'id' => (string)$message->id,
            'sender_name' => $message->sender->name,
            'receiver_name' => $message->receiver->name,
            'message' => $message->message,
        ];
    }
}
